<!-- 编辑弹窗 -->
<template>
  <ele-modal  width="40%" :visible="visible" :close-on-click-modal="true" custom-class="ele-dialog-form"
    :title="isUpdate ? '修改活动信息' : '添加活动信息'" @update:visible="updateVisible" >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-row :gutter="24">
        <el-col :md="24" :sm="24">
          <el-form-item label="活动标题:"  prop="title">
            <el-input clearable v-model="form.title" placeholder="请输入优惠券编号" />
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="开始时间:"  prop="startDate" >
            <el-date-picker style="width:100%"  v-model="form.startDate"  type="datetime" placeholder="选择日期时间"   format="yyyy-MM-dd HH:mm:ss"  @change="changesdate"/> 
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="结束时间:" prop="endDate"  >
            <el-date-picker  style="width:100%" v-model="form.endDate"  type="datetime" placeholder="选择日期时间"  format="yyyy-MM-dd HH:mm:ss" @change="changeedate"/> 
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="活动内容:"  prop="content" style="width:100%" >
            <tinymce-editor v-model="form.content" :init="initData"/>
            <!-- <el-input type="textarea" :rows="4" placeholder="请输入活动内容" v-model="form.content" clearable /> -->
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="banner图:" >
            <el-upload action="#" ref="upload" list-type="picture-card"   :auto-upload="false" :file-list="fileList"  :class="{hide:hideUpload}"  :on-change="handleChange" :limit="limit">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}" style="width:100%;height:100%">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" >
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span v-if="!removeDisable" class="el-upload-list__item-delete" @click="handleRemove(file,fileList)" >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" :modal="false">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
  </el-form>
  <div slot="footer">
    <el-button @click="updateVisible(false)">取消</el-button>
    <el-button type="primary" :loading="loading" v-if="this.btnindex!='3'" @click="save">
      保存
    </el-button>
  </div>
  </ele-modal>
</template>

<script>
  import moment from "moment";
  import upload from "@/components/UpLoad/index.js";
  import TinymceEditor from '@/components/TinymceEditor';
  import { QueryAttchmentByBusinessId,GetGuid,UploadFile} from '@/api/attchment';
  import { AddActive, QueryActiveById, UpdateActive } from '@/api/salesmanager/active';

  export default {
    name: 'ActiveEdit',
    components: {TinymceEditor},
    mixins: [upload],
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      //按钮索引
      btnindex:String,
    },
    data() {
      return {
        // 表单数据
        form: {},
        // 表单验证规则
        rules: {
          title: [{required: true,message: '请输入产品名称',trigger: 'blur'}],
          startDate: [{required: true,message: '请输入产品规格',trigger: 'blur'}],
          endDate: [{required: true,message: '请输入秒杀开始时间',trigger: 'blur'}],
          spikeEDate: [{required: true,message: '请输入秒杀结束时间',trigger: 'blur'}],
          limitQty: [{required: true,message: '请输入限购数量',trigger: 'blur'}],
          price: [{required: true,message: '请输入单价',trigger: 'blur'}],
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        //富文本框初始数据
        initData: {
          height: 500,
          //去掉图片的宽、高
          image_dimensions: false,
          images_upload_handler: (blobInfo, success, failure) => {
           
            //上传力图片对像
            let fdata = new FormData()
            fdata.set('imgType', 51); //图片类型
            fdata.set('attType', 1); //文件类型
            fdata.set('orderIndex', 510); // 顺序
            fdata.set('file', blobInfo.blob());
            // fdata.set('businessId', this.form.id); // 业务ID
            fdata.set('fileName', blobInfo.blob().name); // 文件名称
            
            //上传图片
            UploadFile(fdata).then((res) => {
              if(res!=null && res!=undefined){
                success(res.fileAllPath)
              }else{
                failure(res.msg);
              }
            }).catch(e => {
              this.$message.error(e.message)
            })
          },
        },
      };
    },

    //初始化数据
    mounted(){
      this.limit = 1;
    },
    methods: {
      /* 从后面获取主键 */
      async getId(){
        let id = await GetGuid();
        this.form.id = id;
      },
      //上传图片
      handleChange(file, fileList) {
        let obj = {
          orderIndex: 1, //默认值
          attType: 1, //文件类型(1:图片,2:文件)
          file: file.raw, // 文件流
          fileName: file.name, // 文件名称
          url:file.url,// 文件路径
        }
        //索引
        if(fileList!=null && fileList.length>0){
          obj.orderIndex = fileList.length;
        }
        //业务id 新增页面时，从后台获取Guid
        if(this.form){
          obj.businessId = this.form.id;  
        }
        //文件列表
        this.fileList.push(obj);

        //设置上传图片按钮是否可见
        if(this.fileList!=null && this.fileList!=undefined){
          this.hideUpload = this.fileList.length >= this.limit;
        }else{
          this.hideUpload =false;
        }
      },

      //赋值到附件
      setAttchement(id){
         QueryAttchmentByBusinessId(id).then((d)=>{
          this.fileList = [];
          d.map((item)=>{
            if(item.imgType == 5){
                this.fileList.push({
                id: item.id,
                name: item.fileName,
                url: item.fileAllPath,
                businessId: item.businessId,
                orderIndex: item.orderIndex,
              });
            }
          });
          //设置上传图片按钮是否可见
          this.hideUpload = this.fileList.length >= this.limit;
        });
      },

      /* 保存编辑 */
      save() {
        //校验必填信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}

          this.loading = true;

          //上传图片
          this.fileList.map((f) => {
            if (f.file != undefined) {
              f.fileType = 1;
              f.imgType = 5;
              this.uploadImg(f);
            }
          });

          const saveOrUpdate = this.isUpdate ? UpdateActive : AddActive;
          saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);

              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },

      /* 更新visible */
      updateVisible(value) {
        //更新父组件中的visible的值
        this.$emit('update:visible', value);
      },

      //赋值到页面
      setActive(id){
        QueryActiveById(id)
            .then((res) => {
            this.form = res;
        });
      },

      changesdate(e){
        this.form.startDate = moment(e).format('YYYY-MM-DD HH:mm:ss');
      },

      changeedate(e){
        this.form.endDate = moment(e).format('YYYY-MM-DD HH:mm:ss');
      },
    },

    /* 监听visible属性变化 */
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data && this.data.id){
            //初始化form
            this.form = {};
            this.setActive(this.data.id);
            this.setAttchement(this.data.id);
            this.isUpdate = this.data.id !=null && this.data.id !=undefined;
          } else {
            this.form = {};
            this.fileList=[];
            this.form.content='';
            this.getId();
            this.isUpdate =false;
            this.hideUpload =false;
          }
        } else {
          //移除校验结果
            this.$refs['form'].clearValidate();
        }
      },
    }
  };
</script>

